package com.net.tool;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import com.net.tool.BasicDownload.DownloadListner;
import com.net.tool.BasicDownload.DownloadTable;

public class YogaResDownLoadService extends Service {

	public static final Executor THREAD_POOL_EXECUTOR = Executors
			.newSingleThreadExecutor();

	public int onStartCommand(Intent intent, int flags, int startId) {
		executeCheck();
		return super.onStartCommand(intent, flags, startId);
	}

	public void onCreate() {
		initDownloadListner();
		BasicDownload.registerDownloadListner(mDownloadListner);

		super.onCreate();
	}

	public void onDestroy() {
		BasicDownload.unRegisterDownloadListner(mDownloadListner);
		super.onDestroy();
	}

	DownloadListner mDownloadListner;

	private void initDownloadListner() {

		mDownloadListner = new DownloadListner() {

			NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

			Handler mHandler = new Handler();
			int NOTIFYID = 0xdddd;

			public void stateChange(String taskId, int state, int... is) {

				mHandler.post(new Runnable() {

					public void run() {

						if (isHaveDownloadTask()) {
							Log.d("Notification", "有下载任务");
							sendDownTaskNotification();
						} else if (isHaveInstallTask()) {

							Log.d("Notification", "有安装任务");

							sendInstallTaskNotification();
							stopSelf();
						} else {
							Log.d("Notification", "没有任务了");
							manager.cancel(NOTIFYID);
							stopSelf();
						}

					}
				});

			}

			public void download(String taskId, int progress, int length) {
				// TODO Auto-generated method stub

			}

			public void sendDownTaskNotification() {

				// Notification notification = new Notification();
				// notification.icon = R.drawable.icon;
				// notification.contentView = new RemoteViews(getPackageName(),
				// R.layout.notify_layout);
				//
				// notification.contentView.setTextViewText(R.id.notify_title,
				// getString(R.string.notification_download_title));
				// notification.contentView.setTextViewText(R.id.notify_content,
				// getString(R.string.notification_download_content));
				//
				// notification.contentView.setTextViewText(R.id.notify_time,
				// DailyYogaTools.getSystemCurrentTime().substring(11));
				// notification.flags = Notification.FLAG_AUTO_CANCEL;
				//
				// Intent intent = new Intent(YogaResDownLoadService.this,
				// DownLoadTaskListActivity.class);
				//
				// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				// notification.contentIntent = PendingIntent.getActivity(
				// YogaResDownLoadService.this, 0, intent,
				// PendingIntent.FLAG_UPDATE_CURRENT);
				//
				//	manager.notify(NOTIFYID, notification);

			}

			public void sendInstallTaskNotification() {

				// Notification notification = new Notification();
				// notification.icon = R.drawable.icon;
				// notification.contentView = new RemoteViews(getPackageName(),
				// R.layout.notify_layout);
				//
				// notification.contentView.setTextViewText(R.id.notify_title,
				// getString(R.string.notification_install_title));
				// notification.contentView.setTextViewText(R.id.notify_content,
				// getString(R.string.notification_download_content));
				//
				// notification.contentView.setTextViewText(R.id.notify_time,
				// DailyYogaTools.getSystemCurrentTime().substring(11));
				// notification.flags = Notification.FLAG_AUTO_CANCEL;
				//
				// Intent intent = new Intent(YogaResDownLoadService.this,
				// DownLoadTaskListActivity.class);
				//
				// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				// notification.contentIntent = PendingIntent.getActivity(
				// YogaResDownLoadService.this, 0, intent,
				// PendingIntent.FLAG_UPDATE_CURRENT);
				//
				// manager.notify(NOTIFYID, notification);

			}

			public boolean isHaveDownloadTask() {

				synchronized (DownLoadRunable.class) {
					boolean result = false;
					Cursor cursor = BasicDownload.getSqlite(
							YogaResDownLoadService.this).query(
							DownloadTable.TB_NAME,
							new String[] { DownloadTable.TASKID },
							DownloadTable.TASKSTATE + "=? or "
									+ DownloadTable.TASKSTATE + "=? or "
									+ DownloadTable.TASKSTATE + "=?",
							new String[] {
									BasicDownload.DOWNLOAD_STATE_PREPARE + "",
									BasicDownload.DOWNLOAD_STATE_PENDING + "",
									BasicDownload.DOWNLOAD_STATTE_DOWNLOADING
											+ "", }, null, null, null);

					result = cursor.getCount() > 0;
					cursor.close();

					return result;

				}

			}

			public boolean isHaveInstallTask() {

				synchronized (DownLoadRunable.class) {

					boolean result = false;
					Cursor cursor = BasicDownload
							.getSqlite(YogaResDownLoadService.this)
							.query(DownloadTable.TB_NAME,
									new String[] { DownloadTable.TASKID },
									DownloadTable.TASKSTATE + "=? ",
									new String[] { BasicDownload.DOWNLOAD_STATTE_COMPLATAE
											+ "" }, null, null, null);
					result = cursor.getCount() > 0;
					cursor.close();
					return result;
				}

			}

		};

	}

	protected void executeCheck() {

		synchronized (DownLoadRunable.class) {

			int size = DownLoadRunable.getAllRunningList().size();

			if (size < 1) {
				THREAD_POOL_EXECUTOR.execute(new CheckExcaptionTask(this));
			}

			for (int i = 0; i + size < 2; i++) {
				THREAD_POOL_EXECUTOR.execute(new DownLoadRunable(this));
				Log.d("executeCheck", "添加下载线程");
			}
		}

		mDownloadListner.stateChange("", -1, 0);

	}

	public IBinder onBind(Intent arg0) {
		return null;
	}

}
